import { _decorator, Component, director, Label, tween, Vec3 } from 'cc';
import { emits } from '../data/enums';
import { gameConfig } from '../data/gameConfig';
const { ccclass, property } = _decorator;

@ccclass('GoldCounter')
export class GoldCounter extends Component {
    @property(Label)
    jinbiLabel: Label = null!;

    // 使用中间对象存储动画值
    private _tweenValue = { value: 0 };
    private _targetGold: number = 0;

    onEnable() {
        this._tweenValue.value = gameConfig.jinbiNum;
        this.jinbiLabel.string = gameConfig.jinbiNum.toLocaleString();
        director.on(emits.jinbi, this.addJinbiWithAnimation, this)
        //this.addGoldWithAnimation();
    }

    addJinbiWithAnimation( duration: number = 1.5) {
        this._targetGold = gameConfig.jinbiNum;
        
        // 创建针对_tweenValue的动画
        tween(this._tweenValue)
            .to(duration, { value: this._targetGold }, {
                onUpdate: () => {
                    // 同步数值到_currentGold
                    this.updateDisplay();
                },
                easing: "sineOut"  // 使用 Cocos 内置的缓动类型
            })
            .call(() => {
                this.onGoldUpdateComplete();
            })
            .start();
    }

    private updateDisplay() {
        // 从中间对象获取当前值
        const current = Math.floor(this._tweenValue.value);
        this.jinbiLabel.string = current.toLocaleString();
        
        // 缩放动画（可选）
        tween(this.jinbiLabel.node)
            .to(0.1, { scale: new Vec3(1.1, 1.1, 1) })
            .to(0.1, { scale: Vec3.ONE })
            .start();
    }

    private onGoldUpdateComplete() {
        console.log("金币更新完成！");
    }
}